package pers.qianyu.month_202101.date_20210116;

import pers.qianyu.util.model.*;

/**
 * 61. 旋转链表
 * https://leetcode-cn.com/problems/rotate-list/
 *
 * @author mizzle rain
 * @date 2021-01-16 23:23
 */
public class RotateRight {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null) return head;
        ListNode p = head;
        int n = 0;
        while (p != null) {
            p = p.next;
            n++;
        }
        if (k % n == 0) return head;
        k %= n;
        ListNode left = head, right = head;
        while (k-- > 0) right = right.next;
        if (right == null) return head;
        while (right.next != null) {
            right = right.next;
            left = left.next;
        }
        ListNode root = left.next;
        left.next = null;
        right.next = head;
        return root;
    }
}
